import { getToken, removeToken } from '@/utils/auth';
import { getUserInfo, getPermissions, getAllUser } from '@/api/login';
const isDev = import.meta.env.DEV;

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userId: undefined,
    name: '', // 用户名，必须
    roles: [], // 至少有一个角色身份才能进入系统，必须
    permissions: [], // 用户当前拥有的权限，必须
    company_id: null, // 用户当前公司id
    company_name: '', // 当前公司name
    isLogin: false,
    allPermissions: [
      {
        id: 0,
        key: 'zysq', // 资源申请
        permission: 'resources:apply:page'
      },
      {
        id: 0,
        key: 'sqcl', // 申请处理
        permission: 'resources-manage:handle:page'
      },
      {
        id: 0,
        key: 'zdzy', // 站点资源
        permission: 'resources:sites:page'
      },
      {
        id: 0,
        key: 'zdqybtn', // 弃用按钮权限
        permission: 'resources:sites:giveup'
      },
      {
        id: 0,
        key: 'tfzdqyjl', // 投放站点弃用记录
        permission: 'history-manage:giveup:page'
      },
      {
        id: 0,
        key: 'zdwhls', // 站点维护历史
        permission: 'history-manage:history:page'
      },
      {
        id: 0,
        key: 'fbggsqcl', // FB广告申请处理
        permission: 'resources-manage:fb-advert-application:page'
      },
      {
        id: 0,
        key: 'fbghgl', // FB个号管理
        permission: 'resources:fb-number-management:page'
      },
      {
        id: 0,
        key: 'fbghwhls', // FB个号维护历史
        permission: 'history-manage:fb-number-history:page'
      },
      {
        id: 0,
        key: 'sjzdgl', // 数据字典管理
        permission: 'system:data-dictionary:page'
      },
      {
        id: 0,
        key: 'tdgl', // 团队管理
        permission: 'system:team:page'
      },
      {
        id: 0,
        key: 'yhgl', // 用户管理
        permission: 'system:user:page'
      },
      {
        id: 0,
        key: 'xzzdzy', // 新增站点资源
        permission: 'resources:sites:add'
      },
      {
        id: 0,
        key: 'bjzdzy', // 编辑站点资源
        permission: 'resources:sites:edit'
      },
      {
        id: 0,
        key: 'fbggzhgl', // FB广告账户管理
        permission: 'resources:fb-advert-management:page'
      },
      {
        id: 0,
        key: 'fbggzhwhls', // FB广告账户维护历史
        permission: 'history-manage:resources-fb-advert-history:page'
      },
      {
        id: 0,
        key: 'fbggzhqyjl', // FB广告账户弃用记录
        permission: 'history-manage:resources-fb-advert-giveup:page'
      }
    ], // 权限系统设定的所有权限
    allUserList: [], // 所有用户列表
    userMap: {}, // 权限系统所有用户集合 {id:obj}
    deptMap: {}, // 权限系统所有部门集合 {id:obj}
    companyMap: {} // 权限系统所有公司集合 {id:obj}
  }),
  actions: {
    // 登录 oauth2页面会自动存储cookie
    login(url) {
      location.href = `/oauth2/login?callback=${encodeURIComponent(
        url || location.href
      )}`;
    },
    // 获取公司/部门/用户集合
    getUserList() {
      getAllUser().then(res => {
        this.allUserList = res.data || [];
        this.deepUsers(res.data || []);
      });
    },
    // 递归集合
    deepUsers(list, parrent) {
      list.forEach(item => {
        const { value, children } = item;

        item.id_path = JSON.parse(JSON.stringify(parrent?.id_path || []));
        item.id_path.push(item.value);
        item.id = item.value;
        if (value <= -100000) {
          const newValue = value - 2 * value - 100000;
          item.newValue = newValue;
          this.companyMap[newValue] = item;
        }
        if (value < 0 && value > -100000) {
          this.deptMap[value] = item;
        }
        if (value >= 0) {
          item.order = (this.userMap?.[value]?.order || 0) + 1;
          item.id = this.getOahth2Id(item);
          this.userMap[value] = item;
        }

        if (item.newValue === this.company_id) this.company_name = item.label;

        if (children?.length) this.deepUsers(children, item);
      });
    },
    // 拼接id
    getOahth2Id(data, order) {
      return data.value + '-' + (order || data.order);
    },
    // 获取用户信息
    getInfo() {
      return new Promise(async (resolve, reject) => {
        const userInfo = {
          userName: 'admin',
          roles: ['admin'],
          // permissions: ['*:*:*'] // 超级管理权限
          permissions: ['demo:user:page', 'demo:user:edit'] // 开发中可自行配置权限进行测试
        };

        // 生产环境 （需要测试生产环境流程可以删掉这层if判断）
        // if (!isDev) {
        try {
          const [{ data: info }, { data: permissionsArr }] = await Promise.all([
            getUserInfo(),
            getPermissions()
          ]);
          this.assignPermissions(permissionsArr); // 如果后端没有做获取权限id的接口则取消这一步，并把权限系统对应的权限id配置在allPermissions里
          userInfo.userName = info.name;
          userInfo.roles = ['user']; // 权限系统都是页面和功能级别的权限，暂时不用roles
          userInfo.permissions = this.fetchPermissions(info.perms);
          this.company_id = info.company_id;
          // }
          const { userName, roles, permissions } = userInfo;
          this.userId = info.id;
          this.name = userName;
          this.isLogin = true;
          this.roles = roles;
          this.permissions = permissions;
          resolve(userInfo);
          this.getUserList();
        } catch {
          reject();
        }
      });
    },
    // 根据用户拥有的权限ID获取相应的页面权限
    fetchPermissions(permissionIDs) {
      const permissions = [];
      this.allPermissions.forEach(item => {
        if (permissionIDs.includes(item.id)) {
          permissions.push(item.permission);
        }
      });
      return permissions;
    },
    // 获取权限对应的ID并赋值（由于ID可能会变，所以要从后端获取具体ID）
    assignPermissions(permissions) {
      this.allPermissions.forEach(item => {
        item.id = permissions[item.key];
      });
    },
    // 退出系统
    logOut() {
      this.token = undefined;
      removeToken();
      // location.href = window.baseLocationUrl;
    }
  }
});

export default useUserStore;
